package it.aekidna.cleverplatypus.utils
{
	import it.aekidna.cleverplatypus.domain.IHasChildren;
	import it.aekidna.cleverplatypus.domain.IHasParent;
	
	import mx.collections.ArrayCollection;
	

	public class ChildrenArrayCollection extends ArrayCollection
	{
		private var _parent : IHasChildren;
		
		public function ChildrenArrayCollection( inParent : IHasChildren, inSource : Array = null )
		{
			super(inSource);
			_parent = inParent;
		}
		
		override public function addItemAt( inItem : Object, inIndex : int ) : void
		{
			super.addItemAt( inItem, inIndex );
			if( inItem is IHasParent )
				IHasParent( inItem ).parent = _parent;
		}
		
		override public function removeItemAt( inIndex : int ) : Object
		{
			var item : IHasParent = getItemAt( inIndex ) as IHasParent;
			if( item )
				item.parent = null;
			return super.removeItemAt( inIndex );
		}
		
		override public function removeAll() : void
		{
			for each( var item : Object in toArray() )
			{
				if( item is IHasParent )
					IHasParent( item ).parent = null;
			}
			super.removeAll();
		}
	}
}